/**
 * Copyright 2011 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.codelab;

import java.io.IOException;
import java.io.PrintWriter;
//import java.util.ArrayList;
//import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.Entity;
//import com.google.appengine.api.datastore.Key;
//import com.google.appengine.api.datastore.KeyFactory;

/**
 * This servlet responds to the request corresponding to users. The class
 * creates and manages the User Entity
 * 
 * @author
 */
@SuppressWarnings("serial")
public class ClienteServlet extends BaseServlet {

  private static final Logger logger = Logger.getLogger(ClienteServlet.class.getCanonicalName());

	/**
	 * Get the requested Cliente entities in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining Cliente listing");
		String searchBy = req.getParameter("cliente-searchby");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		if (searchFor == null || searchFor.equals("")) {
			Iterable<Entity> entities = Cliente.getAllClientes();
			out.println(Util.writeJSON(entities));
		} else if (searchBy == null || searchBy.equals("cliente_id")) {
			Iterable<Entity> entities = Cliente.getCliente(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy == null || searchBy.equals("cliente_name")) {
			Iterable<Entity> entities = Cliente.getClientebyName(searchFor);
			out.println(Util.writeJSON(entities));
		}
	}

	/**
	 * Insert the new Cliente
	 */
  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    logger.log(Level.INFO, "Creating Cliente");
    String cliente_id = req.getParameter("cliente_id");
    String cliente_name = req.getParameter("cliente_name");
    String cliente_firstName = req.getParameter("cliente_firstName");
    String cliente_lastName = req.getParameter("cliente_lastName");
    String cliente_phone = req.getParameter("cliente_phone");
    String cliente_cpf = req.getParameter("cliente_cpf");
    String cliente_email = req.getParameter("cliente_email");
    String localidade_id = req.getParameter("localidade_id");
    
  
    Cliente.createOrUpdateCliente(cliente_id,cliente_name, cliente_firstName, cliente_lastName, cliente_phone, cliente_cpf, cliente_email, localidade_id);
  }

	/**
	 * Delete the Cliente
	 */
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
	  	super.doGet(req, resp);
	  	logger.log(Level.INFO, "Deleting Cliente");
	    String clienteKey = req.getParameter("id");
	    PrintWriter out = resp.getWriter();
	    Iterable<Entity> entities = Util.listEntities("Cliente", "cliente_name", clienteKey);
	    try {
	      /*for (Entity e : entities) {
	        if (e != null)
	          out.print("Cannot delete transacao as there are orders associated with this item.");
	        return;
	      }*/
	      Entity e = Cliente.getSingleCliente(clienteKey);
	      Util.deleteFromCache(e.getKey());
	      Util.deleteEntity(e.getKey());
	      out.print("Cliente deleted successfully.");
	    } catch (Exception e) {
	      String msg = Util.getErrorResponse(e);
	      out.print(msg);
	    }
	  }

	/**
	 * Redirect the call to doDelete or doPut method
	 */
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    String action = req.getParameter("action");
    if (action.equalsIgnoreCase("delete")) {
      doDelete(req, resp);
      return;
    } else if (action.equalsIgnoreCase("put")) {
      doPut(req, resp);
      return;
    }
  }
}
